<template>
  <div>
    <div class="wrapper">
      <h1>欢迎登录高铁订餐</h1>
      <div class="form">
        <input type="text" placeholder="手机号" v-model="userInfo.userPhone" 
        @click="showKeyboard = true"
        :focused="showKeyboard"
          readonly/>
        <input
          type="password"
          placeholder="密码"
          
          v-model="userInfo.userPwd"
        />
        <div class="btns">
          <button @click="toLogin">登录</button>
          <button @click="toRegister">注册</button>
        </div>
      </div>
      <div class="right">@copyright by 恰饭啦</div>
    </div>
    <!-- 数字键盘 -->
    <van-number-keyboard
      :show="showKeyboard"
      @blur="showKeyboard = false"
      @input="onInputTel"
      @delete="onDeleteTel"
    />
  </div>
</template>
<script>
import { Toast } from "vant";
export default {
  data() {
    return {
      showKeyboard: false,
      userInfo: {
        userPhone: "",
        userPwd: ""
      }
    };
  },
  methods: {
    // 跳转注册
    toRegister() {
      this.$router.push("/register");
    },
    // 点击登录按钮
    async toLogin() {
      //发请求开始验证账号密码
      if (!this.userInfo.userPhone) return Toast.fail("请先输入手机号");
      if (!this.userInfo.userPwd) return Toast.fail("请先输入密码");
      // 验证手机号
    let validTel = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
    if(!validTel.test(this.userInfo.userPhone)) return Toast.fail('请填写正确的手机号码');
    // 验证密码
    if(this.userInfo.userPwd.length < 6) return Toast.fail('密码至少需要6位');
      const { data: res } = await this.$http.post("login", this.userInfo);
      console.log(res);
      // 验证失败
      if (res.flag == false) {
        return Toast.fail(res.message);
      }
      // 如果是用户登录
      if (res.message == 0) {
        //验证成功，若本地无地址信息跳选地址
        if (!window.localStorage.getItem("user")) {
          window.localStorage.setItem("user", JSON.stringify(res.data));
          //跳转到填写地址信息
          this.$router.push("/verification");
        } else {
          // 若本地有地址信息跳首页
          this.$router.push("/home");
        }
      } else {
        //配送员登录
        // window.localStorage.setItem("user1", JSON.stringify(res.data));
        this.$router.push('/fooddelivery')
      }
    },
    // 输入手机号
    onInputTel(key) {
      this.userInfo.userPhone += key;
    },
    // 点击小键盘删除手机号
    onDeleteTel() {
      this.userInfo.userPhone = this.userInfo.userPhone.slice(
        0,
        this.userInfo.userPhone.length - 1
      );
    }
  }
};
</script>
<style lang="less" scoped>
@import "../assets/css/login.less";
</style>
